﻿using AVCUMPlatform.BLL.Interface;
using AVCUMPlatform.BLL;
using AVCUMPlatform.Entities;
using AVCUMPlatform.Models;
using Microsoft.AspNetCore.Mvc;
using AVCUMPlatform.HelperLibrary;
using Newtonsoft.Json;

namespace AVCUMPlatform.Controllers
{
    /// <summary>
    /// 来源接口
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class MessageTypesController : ControllerBase
    {
        private IMessageTypesBLL _messageTypesBll = BLLContainer.Resolve<IMessageTypesBLL>();
        private ISourceBLL _sourceBll = BLLContainer.Resolve<ISourceBLL>();
        private ISystemInfoBLL _systemInfoBLL = BLLContainer.Resolve<ISystemInfoBLL>();
        private IMessageTmplatesBLL _messageTemplatesBLL = BLLContainer.Resolve<IMessageTmplatesBLL>();
        private IMessageBLL _messageBll = BLLContainer.Resolve<IMessageBLL>();
        /// <summary>
        /// 分页查询消息类型
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="field">排序字段</param>
        /// <param name="order">排序方式</param>
        /// <returns></returns>
        [HttpGet]
        [NoNeedLogin]
        public ActionResult GetList(int page, int limit, string? field, string? order)
        {
            var vmList = new List<MessageTypesVM>();
            var list = _messageTypesBll.GetAll();
            var sendTypes = _systemInfoBLL.GetAll().FirstOrDefault(x=>x.Code == "sendTypes");
            var sendTypeVMs = new List<SendTypesVM>();
            if (sendTypes != null)
            {
                sendTypeVMs = JsonConvert.DeserializeObject<List<SendTypesVM>>(sendTypes.Value);
            }
            var msgTypes = _systemInfoBLL.GetAll().FirstOrDefault(x => x.Code == "msgTypes");
            var msgTypesVMs = new List<SendTypesVM>();
            if (msgTypes != null)
            {
                msgTypesVMs = JsonConvert.DeserializeObject<List<SendTypesVM>>(msgTypes.Value);
            }
            if (!string.IsNullOrWhiteSpace(field) && field != "undefined")
            {
                if (!string.IsNullOrWhiteSpace(order) && order != "undefined")
                {
                    if (order == "desc")
                    {
                        if (field == "id")
                        {
                            list = list.OrderByDescending(x => x.Id).ToList();
                        }
                        else if (field == "sourceStr")
                        {
                            list = list.OrderByDescending(x => x.Source).ToList();
                        }
                        else if (field == "msgTypeStr")
                        {
                            list = list.OrderByDescending(x => x.MsgType).ToList();
                        }
                        else if (field == "sendTypeStr")
                        {
                            list = list.OrderByDescending(x => x.SendType).ToList();
                        }
                        else if (field == "createTime")
                        {
                            list = list.OrderByDescending(x => x.CreateTime).ToList();
                        }
                    }
                    else
                    {
                        if (field == "id")
                        {
                            list = list.OrderBy(x => x.Id).ToList();
                        }
                        else if (field == "sourceStr")
                        {
                            list = list.OrderBy(x => x.Source).ToList();
                        }
                        else if (field == "msgTypeStr")
                        {
                            list = list.OrderBy(x => x.MsgType).ToList();
                        }
                        else if (field == "sendTypeStr")
                        {
                            list = list.OrderBy(x => x.SendType).ToList();
                        }
                        else if (field == "createTime")
                        {
                            list = list.OrderBy(x => x.CreateTime).ToList();
                        }
                    }
                }
            }
            var count = list.Count();
            list = list.Skip((page - 1) * limit).Take(limit).ToList();
            var msgs = _messageBll.GetAll();
            var messageTemplates = _messageTemplatesBLL.GetAll();
            foreach (var messageType in list)
            {
                var exist = msgs.FirstOrDefault(x => x.Msgtype == messageType.Id);
                var source = _sourceBll.Get(messageType.Source);
                var sendTypeVM = sendTypeVMs != null ? sendTypeVMs.FirstOrDefault(x => x.value == messageType.SendType.ToString()) : null;
                var msgTypeVM = msgTypesVMs != null ? msgTypesVMs.FirstOrDefault(x => x.value == messageType.MsgType.ToString()) : null;
                var messageTemplate = messageTemplates.FirstOrDefault(x => x.Id == messageType.MessageTemplateId);
                var vm = new MessageTypesVM()
                {
                    Id = messageType.Id,
                    Code = messageType.Code,
                    Name = messageType.Name,
                    Source = messageType.Source,
                    SourceStr = source != null ? $"{source.Name}({source.Code})" : string.Empty,
                    MsgType = messageType.MsgType,
                    MsgTypeStr = msgTypeVM != null ? $"{msgTypeVM.name}" : string.Empty,
                    SendType = messageType.SendType,
                    SendTypeStr = sendTypeVM != null ? $"{sendTypeVM.name}" : string.Empty,
                    MessageTemplateId = messageType.MessageTemplateId,
                    MessageTemplateName = messageTemplate != null ? messageTemplate.Name : string.Empty,
                    CreateTime = messageType.CreateTime,
                    Enable = messageType.Enable,
                    EnableStr = messageType.Enable == 1 ? "启用" : "禁用",
                    IsCanDelete = exist == null || exist.Id <= 0 ? 1 : 2,
                };
                vmList.Add(vm);
            }
            var obj = new { code = 0, count, data = vmList, msg = "" };
            return new JsonResult(obj);
        }

        /// <summary>
        /// 查询所有消息类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [NoNeedLogin]
        public ActionResult GetAll(int sourceId)
        {
            var vmList = new List<MessageTypesVM>();
            var messageTypeList = new List<MessageTypes>();
            if (sourceId > 0)
            {
                messageTypeList = _messageTypesBll.GetAll().Where(x => x.Source == sourceId).ToList();
            }
            else
            {
                messageTypeList = _messageTypesBll.GetAll();
            }
            var sendTypes = _systemInfoBLL.GetAll().FirstOrDefault(x => x.Code == "sendTypes");
            var sendTypeVMs = new List<SendTypesVM>();
            if (sendTypes != null)
            {
                sendTypeVMs = JsonConvert.DeserializeObject<List<SendTypesVM>>(sendTypes.Value);
            }
            var msgTypes = _systemInfoBLL.GetAll().FirstOrDefault(x => x.Code == "msgTypes");
            var msgTypesVMs = new List<SendTypesVM>();
            if (msgTypes != null)
            {
                msgTypesVMs = JsonConvert.DeserializeObject<List<SendTypesVM>>(msgTypes.Value);
            }
            var sourceList = _sourceBll.GetAll();
            foreach (var messageType in messageTypeList)
            {
                var source = sourceList.FirstOrDefault(x => x.Id == messageType.Source);
                var sendTypeVM = sendTypeVMs != null ? sendTypeVMs.FirstOrDefault(x => x.value == messageType.SendType.ToString()) : null;
                var msgTypeVM = msgTypesVMs != null ? msgTypesVMs.FirstOrDefault(x => x.value == messageType.MsgType.ToString()) : null;
                var vm = new MessageTypesVM()
                {
                    Id = messageType.Id,
                    Code = messageType.Code,
                    Name = messageType.Name,
                    Source = messageType.Source,
                    SourceStr = source != null ? $"{source.Name}({source.Code})" : string.Empty,
                    MsgType = messageType.MsgType,
                    MsgTypeStr = msgTypeVM != null ? $"{msgTypeVM.name}" : string.Empty,
                    SendType = messageType.SendType,
                    SendTypeStr = sendTypeVM != null ? $"{sendTypeVM.name}" : string.Empty,
                    MessageTemplateId = messageType.MessageTemplateId,
                    CreateTime = messageType.CreateTime,
                    Enable = messageType.Enable,
                    EnableStr = messageType.Enable == 1 ? "启用" : "禁用"
                };
                vmList.Add(vm);
            }
            var obj = new { code = 0, count = vmList.Count, data = vmList, msg = "" };
            return new JsonResult(obj);
        }

        /// <summary>
        /// 根据id查询消息类型
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [NoNeedLogin]
        public ActionResult GetDetailById(int id)
        {
            var messageType = _messageTypesBll.Get(id);
            var sendTypeVMs = new List<SendTypesVM>();
            var sendTypes = _systemInfoBLL.GetAll().FirstOrDefault(x => x.Code == "sendTypes");
            if (sendTypes != null)
            {
                sendTypeVMs = JsonConvert.DeserializeObject<List<SendTypesVM>>(sendTypes.Value);
            }
            var msgTypes = _systemInfoBLL.GetAll().FirstOrDefault(x => x.Code == "msgTypes");
            var msgTypesVMs = new List<SendTypesVM>();
            if (msgTypes != null)
            {
                msgTypesVMs = JsonConvert.DeserializeObject<List<SendTypesVM>>(msgTypes.Value);
            }
            var source = _sourceBll.Get(messageType.Source);
            var sendTypeVM = sendTypeVMs != null ? sendTypeVMs.FirstOrDefault(x => x.value == messageType.SendType.ToString()) : null;
            var msgTypeVM = msgTypesVMs != null ? msgTypesVMs.FirstOrDefault(x => x.value == messageType.MsgType.ToString()) : null;
            var vm = new MessageTypesVM()
            {
                Id = messageType.Id,
                Code = messageType.Code,
                Name = messageType.Name,
                Source = messageType.Source,
                SourceStr = source != null ? $"{source.Name}({source.Code})" : string.Empty,
                MsgType = messageType.MsgType,
                MsgTypeStr = msgTypeVM != null ? $"{msgTypeVM.name}" : string.Empty,
                SendType = messageType.SendType,
                SendTypeStr = sendTypeVM != null ? $"{sendTypeVM.name}" : string.Empty,
                MessageTemplateId = messageType.MessageTemplateId,
                CreateTime = messageType.CreateTime,
                Enable = messageType.Enable,
                EnableStr = messageType.Enable == 1 ? "启用" : "禁用"
            };
            if (messageType.MessageTemplateId != null && messageType.MessageTemplateId.Value > 0)
            {
                var messageTemplate = _messageTemplatesBLL.Get(messageType.MessageTemplateId.Value);
                if (messageTemplate != null && messageTemplate.Id > 0)
                {
                    vm.SendJson = messageTemplate.SendJson;
                }
            }
            if (vm.SendJson == null)
            {
                vm.SendJson = string.Empty;
            }
            var obj = new { code = 0, count = 1 , data = vm, msg = "" };
            return new JsonResult(obj);
        }

        /// <summary>
        /// 根据code查询消息类型
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultModel GetDetailByCode(string code)
        {
            var res = new ResultModel();
            var messageType = _messageTypesBll.GetAll().FirstOrDefault(x => x.Code == code);
            if (messageType == null)
            {
                res.code = -1;
                res.data = new MessageTypesVM();
                res.msg = "消息类型不存在";
                return res;
            }
            var sendJson = string.Empty;
            if (messageType.MessageTemplateId != null && messageType.MessageTemplateId.Value > 0)
            {
                var messageTemplate = _messageTemplatesBLL.Get(messageType.MessageTemplateId.Value);
                if (messageTemplate != null && messageTemplate.Id > 0)
                {
                    sendJson = messageTemplate.SendJson;
                }
            }
            if (sendJson == null)
            {
                sendJson = string.Empty;
            }
            res.code = 0;
            res.data = sendJson;
            res.msg = "";
            return res;
        }
        /// <summary>
        /// 新增或编辑
        /// </summary>
        /// <param name="messageTypes"></param>
        /// <returns></returns>
        [HttpPost]
        [NoNeedLogin]
        public ResultModel AddOrUpdate(MessageTypes messageTypes)
        {
            var ret = new ResultModel();
            if (messageTypes.Id > 0)
            {
                var exist = _messageTypesBll.Get(messageTypes.Id);
                exist.Code = messageTypes.Code;
                exist.Name = messageTypes.Name;
                exist.MsgType = messageTypes.MsgType;
                exist.SendType = messageTypes.SendType;
                exist.Source = messageTypes.Source;
                exist.ModifyTime = DateTime.Now.ToYMDHMS();
                exist.Enable = messageTypes.Enable;
                _messageTypesBll.Update(exist);
            }
            else
            {
                var allMessageTypes = _messageTypesBll.GetAll();
                if (allMessageTypes != null && allMessageTypes.Any(x=>x.Code == messageTypes.Code))
                {
                    ret.code = -1;
                    ret.msg = "存在重复的类型编号";
                    return ret;
                }
                else
                {
                    messageTypes.CreateTime = DateTime.Now.ToYMDHMS();
                    _messageTypesBll.Add(messageTypes);
                }
            }
            ret.code = 1;
            return ret;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [NoNeedLogin]
        public ResultModel Delete(int id)
        {
            var ret = new ResultModel();
            ret.code = _messageTypesBll.Delete(new List<int>() { id }) ? 1 : -1;
            if (ret.code == -1)
            {
                ret.msg = "删除失败";
            }
            return ret;
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpGet]
        [NoNeedLogin]
        public ResultModel BatchDelete(string ids)
        {
            var ret = new ResultModel();
            var idList = ids.Split(',').Select(x => Convert.ToInt32(x)).ToList();
            ret.code = _messageTypesBll.Delete(idList) ? 1 : -1;
            if (ret.code == -1)
            {
                ret.msg = "删除失败";
            }
            return ret;
        }

        /// <summary>
        /// 新增或编辑消息模板
        /// </summary>
        /// <param name="rm"></param>
        /// <returns></returns>
        [HttpPost]
        [NoNeedLogin]
        public ResultModel AddOrUpdateMessageTemplate(AddOrUpdateMessageTemplateRM rm)
        {
            var ret = new ResultModel();
            if (rm.Id <= 0)
            {
                ret.code = -1;
                ret.msg = "消息类型不存在";
                return ret;
            }

            var exist = _messageTypesBll.Get(rm.Id);
            if (exist == null || exist.Id <= 0)
            {
                ret.code = -1;
                ret.msg = "消息类型不存在";
                return ret;
            }
            exist.MessageTemplateId = rm.MessageTemplateId;
            exist.ModifyTime = DateTime.Now.ToYMDHMS();
            var flag = _messageTypesBll.Update(exist);
            ret.code = flag ? 1 : -1;
            ret.msg = flag ? string.Empty : "更新失败";
            return ret;
        }

        /// <summary>
        /// 是否能删除消息模板
        /// </summary>
        /// <param name="templateId"></param>
        /// <returns></returns>
        [HttpGet]
        [NoNeedLogin]
        public ResultModel IsCanDeleteMessageTemplate(int templateId)
        {
            var ret = new ResultModel();
            var exist = _messageTypesBll.GetAll().FirstOrDefault(x => x.MessageTemplateId == templateId);
            if (exist != null && exist.Id > 0)
            {
                ret.code = -1;
                return ret;
            }
            ret.code = 1;
            return ret;
        }
    }
}
